"""
@Project:efficient
@File:serializer.py
@Author:韩晓雷
@Date:10:00
"""

import re
from rest_framework import serializers
from user.models import *
from rest_framework.validators import ValidationError


# 登录日志
class ConLogSer(serializers.ModelSerializer):
    user = serializers.PrimaryKeyRelatedField(queryset=UserModel.objects.all())
    user_account = serializers.SerializerMethodField(read_only=True)

    def get_user_account(self, obj):
        return obj.user.account

    class Meta:
        model = ConLogModel
        fields = "__all__"


# 操作日志
class ULogSer(serializers.ModelSerializer):
    user = serializers.PrimaryKeyRelatedField(queryset=UserModel.objects.all())
    user_name = serializers.SerializerMethodField(read_only=True)

    def get_user_name(self, obj):
        return obj.user.name

    class Meta:
        model = ULogModel
        fields = "__all__"


# 菜单
class MenuSer(serializers.ModelSerializer):
    role = serializers.PrimaryKeyRelatedField(queryset=RoleModel.objects.all())
    role_name = serializers.SerializerMethodField(read_only=True)

    def get_role_name(self, obj):
        return obj.role.name

    class Meta:
        model = MenuModel
        fields = "__all__"

    def validate(self, attrs):
        name = attrs.get("name")
        if not re.findall(r"[\u4e00-\u9fa5]{1,9}", name):
            raise ValidationError(f'{name}名称由2到9为汉字组成')
        return attrs


# 角色
class RoleSer(serializers.ModelSerializer):

    class Meta:
        model = RoleModel
        fields = "__all__"

    def validate(self, attrs):
        name = attrs.get("rolename")
        if not re.findall(r"[\u4e00-\u9fa5]{1,9}", name):
            raise ValidationError(f'{name}名称由2到9为汉字组成')
        return attrs



